package com.afd.ozblip.activity;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import com.afd.ozblip.image.LoadImage;
import com.afd.ozblip.net.HttpUtil;
import com.afd.ozblip.util.AsyncAction;
import com.afd.ozblip.util.AsyncLoadData;
import com.afd.ozblip.util.Constants;
import com.afd.ozblip.util.ParseJson;
import com.afd.ozblip.util.SharedUtil;
import com.afd.ozblip.util.StringUtil;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Base64;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

public class UserUnloginActivity extends BaseActivity implements
		OnTabActivityResultListener {

	/****************** 视图变量 **************************/
	private LinearLayout userMainLayout;
	private ImageView userImageIv;
	private TextView userNameTv;
	private TextView userLevelTv;
	private TextView userPointTv;
	private EditText userSignatureEt;
	private ImageView userSignatureIv;
	private LinearLayout toLoginLayout;
	private LinearLayout toRegisterLayout;
	private LinearLayout vipLayout;
	private LinearLayout couponLayout;
	private LinearLayout collectLayout;
	private LinearLayout signLayout;
	private LinearLayout reviewLayout;
	private LinearLayout draftsterLayout;
	private LinearLayout photoLayout;
	private LinearLayout integralLayout;
	private LinearLayout messageLayout;
	private LinearLayout contactsLayout;

	private LinearLayout commonRight;
	/****************** 数据变量 **************************/
	private String fileBase64;
	private Bitmap headBitmap;
	private String signatureStr;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.user_center);
		this.userMainLayout = (LinearLayout) findViewById(R.id.ll_user_center_main);
		View logined = LayoutInflater.from(this).inflate(
				R.layout.user_info_logined, null);
		View unlogin = LayoutInflater.from(this).inflate(
				R.layout.user_info_unlogin, null);
		this.userMainLayout.removeAllViews();
		ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(
				ViewGroup.LayoutParams.MATCH_PARENT,
				ViewGroup.LayoutParams.MATCH_PARENT);
		if (isLogin) {
			this.userMainLayout.addView(logined, lp);
			findLoginedViews(logined);
			setLoginedListeners();
			setLoginedView();
		} else {
			this.userMainLayout.addView(unlogin, lp);
			// 寻找视图
			findViews(unlogin);
			// 设置监听
			setListeners();
		}
		// 获取参数
		getBundle();
	}

	@Override
	protected void onResume() {
		super.onResume();
		ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(
				ViewGroup.LayoutParams.MATCH_PARENT,
				ViewGroup.LayoutParams.MATCH_PARENT);
		if (isLogin) {
			View logined = LayoutInflater.from(this).inflate(
					R.layout.user_info_logined, null);
			this.userMainLayout.removeAllViews();
			this.userMainLayout.addView(logined, lp);
			findLoginedViews(logined);
			setLoginedListeners();
			setUserImage();
			setLoginedView();
		} else {
			View unlogin = LayoutInflater.from(this).inflate(
					R.layout.user_info_unlogin, null);
			this.userMainLayout.removeAllViews();
			this.userMainLayout.addView(unlogin, lp);
			// 寻找视图
			findViews(unlogin);
			// 设置监听
			setListeners();
		}
	}

	/**
	 * 寻找未登录页面视图
	 */
	public void findViews(View view) {
		this.toLoginLayout = (LinearLayout) view
				.findViewById(R.id.ll_user_toLogin_btn);
		this.toRegisterLayout = (LinearLayout) view
				.findViewById(R.id.ll_user_toRegister_btn);
		this.vipLayout = (LinearLayout) view.findViewById(R.id.ll_user_vip);
		this.couponLayout = (LinearLayout) view
				.findViewById(R.id.ll_user_coupon);
		this.collectLayout = (LinearLayout) view
				.findViewById(R.id.ll_user_collect);
		this.signLayout = (LinearLayout) view.findViewById(R.id.ll_user_sign);
		this.reviewLayout = (LinearLayout) view
				.findViewById(R.id.ll_user_review);
		this.draftsterLayout = (LinearLayout) view
				.findViewById(R.id.ll_user_drafts);
		this.photoLayout = (LinearLayout) view.findViewById(R.id.ll_user_photo);
		this.integralLayout = (LinearLayout) view
				.findViewById(R.id.ll_user_integral);
		this.messageLayout = (LinearLayout) view
				.findViewById(R.id.ll_user_message);
	}

	/**
	 * 设置未登录页面监听
	 */
	public void setListeners() {
		View.OnClickListener unLoginClick = new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				switch (v.getId()) {
				case R.id.ll_user_toLogin_btn:
					Intent loginIntent = new Intent(UserUnloginActivity.this,
							TabLoginActivity.class);
					startActivity(loginIntent);
					break;
				case R.id.ll_user_toRegister_btn:
					Intent registerIntent = new Intent(
							UserUnloginActivity.this, RegisterActivity.class);
					startActivity(registerIntent);
					break;
				case R.id.ll_user_vip:
				case R.id.ll_user_coupon:
				case R.id.ll_user_collect:
				case R.id.ll_user_sign:
				case R.id.ll_user_review:
				case R.id.ll_user_drafts:
				case R.id.ll_user_photo:
				case R.id.ll_user_integral:
				case R.id.ll_user_message:
					showShortToast(UserUnloginActivity.this, "温馨提示：请先登录");
					break;

				default:
					break;
				}
			}
		};
		this.toLoginLayout.setOnClickListener(unLoginClick);
		this.toRegisterLayout.setOnClickListener(unLoginClick);
		this.vipLayout.setOnClickListener(unLoginClick);
		this.couponLayout.setOnClickListener(unLoginClick);
		this.collectLayout.setOnClickListener(unLoginClick);
		this.signLayout.setOnClickListener(unLoginClick);
		this.reviewLayout.setOnClickListener(unLoginClick);
		this.draftsterLayout.setOnClickListener(unLoginClick);
		this.photoLayout.setOnClickListener(unLoginClick);
		this.integralLayout.setOnClickListener(unLoginClick);
		this.messageLayout.setOnClickListener(unLoginClick);

	}

	/**
	 * TODO 寻找登录页面视图
	 */
	public void findLoginedViews(View view) {
		this.commonRight = (LinearLayout) view
				.findViewById(R.id.ll_common_right);
		this.userImageIv = (ImageView) findViewById(R.id.iv_user_image);
		this.userNameTv = (TextView) findViewById(R.id.tv_user_name);
		this.userLevelTv = (TextView) findViewById(R.id.tv_user_level);
		this.userPointTv = (TextView) findViewById(R.id.tv_user_point);
		this.userSignatureEt = (EditText) findViewById(R.id.et_user_signature);
		this.userSignatureIv = (ImageView) findViewById(R.id.iv_user_signature);
		this.vipLayout = (LinearLayout) view.findViewById(R.id.ll_user_vip);
		this.couponLayout = (LinearLayout) view
				.findViewById(R.id.ll_user_coupon);
		this.collectLayout = (LinearLayout) view
				.findViewById(R.id.ll_user_collect);
		this.signLayout = (LinearLayout) view.findViewById(R.id.ll_user_sign);
		this.reviewLayout = (LinearLayout) view
				.findViewById(R.id.ll_user_review);
		this.draftsterLayout = (LinearLayout) view
				.findViewById(R.id.ll_user_drafts);
		this.photoLayout = (LinearLayout) view.findViewById(R.id.ll_user_photo);
		this.integralLayout = (LinearLayout) view
				.findViewById(R.id.ll_user_integral);
		this.messageLayout = (LinearLayout) view
				.findViewById(R.id.ll_user_message);
		this.contactsLayout = (LinearLayout) view
				.findViewById(R.id.ll_user_contacts);
	}

	/**
	 * 设置登录页面监听
	 */
	public void setLoginedListeners() {
		View.OnClickListener loginedClick = new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				switch (v.getId()) {
				case R.id.iv_user_image:
					showImageMenuDialog();
					break;
				case R.id.iv_user_signature:
					userSignatureEt.setEnabled(true);
					userSignatureEt.setFocusable(true);
					userSignatureEt.setFocusableInTouchMode(true);
					userSignatureEt.requestFocus();
					break;
				case R.id.ll_user_vip:
					Intent vipListIntent = new Intent(UserUnloginActivity.this,
							UserVipListActivity.class);
					startActivity(vipListIntent);
					break;
				case R.id.ll_user_coupon:
					Intent couponIntent = new Intent(UserUnloginActivity.this,
							UserCouponActivity.class);
					startActivity(couponIntent);
					break;
				case R.id.ll_user_collect:
					Intent collectIntent = new Intent(UserUnloginActivity.this,
							UserCollectActivity.class);
					collectIntent.putExtra("userId", commonUserInfo.getUserId());
					startActivity(collectIntent);
					break;
				case R.id.ll_user_sign:
					Intent signedIntent = new Intent(UserUnloginActivity.this,
							UserSignedActivity.class);
					signedIntent.putExtra("userId", commonUserInfo.getUserId());
					startActivity(signedIntent);
					break;
				case R.id.ll_user_review:
					Intent reviewIntent = new Intent(UserUnloginActivity.this,
							UserReviewListActivity.class);
					reviewIntent.putExtra("userId", commonUserInfo.getUserId());
					startActivity(reviewIntent);
					break;
				case R.id.ll_user_drafts:
					Intent draftsIntent = new Intent(UserUnloginActivity.this,
							UserDraftsActivity.class);
					startActivity(draftsIntent);
					break;
				case R.id.ll_user_photo:
					Intent photoIntent = new Intent(UserUnloginActivity.this,
							UserPhotoActivity.class);
					photoIntent.putExtra("userId", commonUserInfo.getUserId());
					startActivity(photoIntent);
					break;
				case R.id.ll_user_integral:
					Intent integralIntent = new Intent(
							UserUnloginActivity.this,
							UserIntegralActivity.class);
					startActivity(integralIntent);
					break;
				case R.id.ll_user_message:
					Intent messageIntent = new Intent(UserUnloginActivity.this,
							UserMsgListActivity.class);
					startActivity(messageIntent);
					break;
				case R.id.ll_user_contacts:
					Intent contactsIntent = new Intent(
							UserUnloginActivity.this,
							UserContactsActivity.class);
					startActivity(contactsIntent);
					break;
				case R.id.ll_common_right:
					Intent indexIntent = new Intent(UserUnloginActivity.this,
							IndexActivity.class);
					indexIntent.putExtra(IndexActivity.INTENT_TAB_CHANGE, 3);
					isLogin = false;
					commonUserInfo = null;
					//清除存储的信息
					SharedUtil.clearUserInfo(UserUnloginActivity.this);
					startActivity(indexIntent);
					break;

				default:
					break;
				}
			}
		};
		this.userImageIv.setOnClickListener(loginedClick);
		this.userSignatureIv.setOnClickListener(loginedClick);
		this.vipLayout.setOnClickListener(loginedClick);
		this.couponLayout.setOnClickListener(loginedClick);
		this.collectLayout.setOnClickListener(loginedClick);
		this.signLayout.setOnClickListener(loginedClick);
		this.reviewLayout.setOnClickListener(loginedClick);
		this.draftsterLayout.setOnClickListener(loginedClick);
		this.photoLayout.setOnClickListener(loginedClick);
		this.integralLayout.setOnClickListener(loginedClick);
		this.messageLayout.setOnClickListener(loginedClick);
		this.commonRight.setOnClickListener(loginedClick);
		this.contactsLayout.setOnClickListener(loginedClick);

		this.userSignatureEt
				.setOnEditorActionListener(new TextView.OnEditorActionListener() {

					@Override
					public boolean onEditorAction(TextView v, int actionId,
							KeyEvent event) {
						signatureStr = userSignatureEt.getText().toString();
						requestUpdateUserData();
						return false;
					}
				});

	}

	/**
	 * 设置登录后界面视图
	 */
	private void setLoginedView() {
		if (commonUserInfo != null) {
			String headUrl = commonUserInfo.getUserHeadUrl();
			if (!StringUtil.isNullOrEmpty(headUrl)) {
				LoadImage li = new LoadImage(this);
				li.addTask(Constants.WEB_PATH + headUrl, this.userImageIv);
			}
			String nickName = commonUserInfo.getUserNickName();
			if (!StringUtil.isNullOrEmpty(nickName)) {
				this.userNameTv.setText(nickName);
			}
			String userLevel = commonUserInfo.getUserLevel();
			if (!StringUtil.isNullOrEmpty(userLevel)) {
				this.userLevelTv.setText(userLevel);
			}
			String userPoint = commonUserInfo.getUserIntegral();
			if (!StringUtil.isNullOrEmpty(userPoint)) {
				this.userPointTv.setText(userPoint);
			}
			String userSignature = commonUserInfo.getUserSignature();
			if (!StringUtil.isNullOrEmpty(userSignature)) {
				this.userSignatureEt.setText(userSignature);
			}

		}
	}

	/**
	 * 获取传递的参数
	 */
	private void getBundle() {
		// Intent intent = getIntent();
	}

	public static final int PHOTOHRAPH = 1;// 拍照
	public static final int PHOTOZOOM = 2; // 缩放
	public static final int PHOTORESOULT = 3;// 结果

	public static final String IMAGE_UNSPECIFIED = "image/*";

	private byte[] mContent;

	private void showImageMenuDialog() {
		final String[] arrayFruit = new String[] { "相机拍摄", "手机相册" };

		final Dialog alertDialog = new AlertDialog.Builder(
				UserUnloginActivity.this).setTitle("图片来源")
				.setIcon(android.R.drawable.ic_dialog_info)
				.setItems(arrayFruit, new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						switch (which) {
						case 0:
							Intent cameraI = new Intent(
									MediaStore.ACTION_IMAGE_CAPTURE);
							cameraI.putExtra(MediaStore.EXTRA_OUTPUT, Uri
									.fromFile(new File(Environment
											.getExternalStorageDirectory(),
											"temp.jpg")));
							getParent().startActivityForResult(cameraI,
									PHOTOHRAPH);
							break;
						case 1:
							// Intent pictureI = new Intent(Intent.ACTION_PICK,
							// null);
							// pictureI.setDataAndType(
							// MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
							// IMAGE_UNSPECIFIED);
							// getParent().startActivityForResult(pictureI,
							// PHOTOZOOM);
							Intent indexIntent = new Intent(
									UserUnloginActivity.this,
									ChoosePhotoActivity.class);
							getParent().startActivityForResult(indexIntent, 4);
							break;

						default:
							break;
						}
						// if (which == 0) {
						// Intent getImageByCamera = new Intent(
						// "android.media.action.IMAGE_CAPTURE");
						// getParent().startActivityForResult(
						// getImageByCamera, 1);
						// } else {
						// Intent getImage = new Intent(
						// Intent.ACTION_GET_CONTENT);
						// getImage.addCategory(Intent.CATEGORY_OPENABLE);
						// getImage.setType("image/*");
						// getImage.putExtra("return-data", true);
						// getParent().startActivityForResult(getImage, 0);
						// }
					}
				}).create();
		alertDialog.show();
	}

	// 剪切图片
	public void startPhotoZoom(Uri uri) {
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, IMAGE_UNSPECIFIED);
		intent.putExtra("crop", "circle");
		// aspectX aspectY 是宽高的比例
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		// // outputX outputY 是裁剪图片宽高
		intent.putExtra("outputX", 250);
		intent.putExtra("outputY", 250);
		intent.putExtra("return-data", true);
		getParent().startActivityForResult(intent, PHOTORESOULT);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (data == null) {
			return;
		}
		if (requestCode == 4) {
			Bundle extras = data.getExtras();
			if (extras != null) {
				System.out.println(extras.getString("data"));
			}
		}
	}

	@Override
	public void onTabActivityResult(int requestCode, int resultCode,
			Intent intent) {

		if (requestCode == PHOTOHRAPH) {
			// 设置文件保存路径这里放在跟目录下
			File picture = new File(Environment.getExternalStorageDirectory()
					+ "/temp.jpg");
			startPhotoZoom(Uri.fromFile(picture));
		}
		if (intent == null) {
			return;
		}
		if (requestCode == 4) {
			Bundle extras = intent.getExtras();
			if (extras != null) {
				System.out.println(extras.getString("data"));
			}
		}
		// 相册
		// 读取相册缩放图片
		if (requestCode == PHOTOZOOM) {
			startPhotoZoom(intent.getData());
		}

		// 处理结果
		if (requestCode == PHOTORESOULT) {
			Bundle extras = intent.getExtras();
			if (extras != null) {
				headBitmap = extras.getParcelable("data");
				userImageIv.setImageBitmap(headBitmap);
				ByteArrayOutputStream bStream = new ByteArrayOutputStream();
				headBitmap.compress(CompressFormat.JPEG, 100, bStream);

				byte[] bytes = bStream.toByteArray();
				fileBase64 = Base64.encodeToString(bytes, Base64.DEFAULT);
				// // 设置创意类型
				// ideaType = TYPE_IMAGE;
				// uploadFile();
			}
		}
		// switch (requestCode) {
		// case 0:
		// try {
		// ContentResolver resolver = getContentResolver();
		// // 获得图片的uri
		// System.out.println(intent + "^^^^^^^^^");
		// Uri originalUri = intent.getData();
		// // 将图片内容解析成字节数组
		// mContent = readStream(resolver.openInputStream(Uri
		// .parse(originalUri.toString())));
		// if (mContent == null) {
		// return;
		// }
		// // 将字节数组转换为ImageView可调用的Bitmap对象
		// headBitmap = getPicFromBytes(mContent, null);
		// // //把得到的图片绑定在控件上显示
		// // this.ideaImageIv.setImageBitmap(headBitmap);
		// // BitmapDrawable bd = new BitmapDrawable(getResources(),
		// // headBitmap);
		// userImageIv.setImageBitmap(headBitmap);
		// // imgDeleteIv.setVisibility(0);
		// fileBase64 = Base64.encodeToString(mContent, Base64.DEFAULT);
		// requestUpdateUserData();
		// } catch (Exception e) {
		// e.printStackTrace();
		// }
		// break;
		// case 1:
		// try {
		// if (intent == null) {
		// return;
		// }
		// Bundle extras = intent.getExtras();
		// headBitmap = (Bitmap) extras.get("data");
		// ByteArrayOutputStream baos = new ByteArrayOutputStream();
		// headBitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
		// mContent = baos.toByteArray();
		// fileBase64 = Base64.encodeToString(mContent, Base64.DEFAULT);
		// // 设置创意类型
		// // 把得到的图片绑定在控件上显示
		// // this.ideaImageIv.setImageBitmap(headBitmap);
		// // BitmapDrawable bd = new BitmapDrawable(getResources(),
		// // headBitmap);
		// // ideaImageIv.setBackgroundDrawable(bd);
		// userImageIv.setImageBitmap(headBitmap);
		// // imgDeleteIv.setVisibility(0);
		// requestUpdateUserData();
		// } catch (Exception e) {
		// e.printStackTrace();
		// }
		//
		// break;
		//
		// default:
		// break;
		// }
	}

	private void setUserImage() {
		// 将字节数组转换为ImageView可调用的Bitmap对象
		if (commonContent != null) {
			byte[] mContent = commonContent;
			headBitmap = getPicFromBytes(mContent, null);
			userImageIv.setImageBitmap(headBitmap);
			fileBase64 = Base64.encodeToString(mContent, Base64.DEFAULT);
			// 清空此内容，以免占内存
			commonContent = null;
			requestUpdateUserData();
		}
	}

	public static Bitmap getPicFromBytes(byte[] bytes,
			BitmapFactory.Options opts) {
		if (bytes != null)
			if (opts != null)
				return BitmapFactory.decodeByteArray(bytes, 0, bytes.length,
						opts);
			else
				return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
		return null;
	}

	public static byte[] readStream(InputStream inStream) throws Exception {
		byte[] buffer = new byte[1024];
		int len = -1;
		ByteArrayOutputStream outStream = new ByteArrayOutputStream();
		while ((len = inStream.read(buffer)) != -1) {
			outStream.write(buffer, 0, len);
		}
		byte[] data = outStream.toByteArray();
		outStream.close();
		inStream.close();
		return data;

	}

	/**
	 * 获取评论列表数据
	 */
	private void requestUpdateUserData() {
		if (commonUserInfo == null) {
			return;
		}
		AsyncLoadData ald = new AsyncLoadData(this, "修改中...",
				new AsyncAction() {

					@Override
					public void doLoad() throws Exception {
						// 获取提交参数
						Map<String, Object> nearbyBusinessParamMap = new HashMap<String, Object>();
						nearbyBusinessParamMap.put("userId",
								commonUserInfo.getUserId());
						nearbyBusinessParamMap.put("headImg", fileBase64);
						nearbyBusinessParamMap.put("signature", signatureStr);
						// 发送请求
						byte[] commentItemList = HttpUtil.requestByPost(
								UserUnloginActivity.this,
								Constants.UPDATE_USER_API,
								nearbyBusinessParamMap);
						if (commentItemList != null) {
							new ParseJson().parseAddResultJson(commentItemList);
						}
					}

					@Override
					public void loadEnd() throws Exception {
						userSignatureEt.setFocusable(false);
					}

				});
		ald.execute(0);
	}
}